package system;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/getCompletion")
public class getCompletion extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	int type=Integer.parseInt(req.getParameter("type"));	
    	
		String testid=req.getParameter("testid");
		String studentid=req.getParameter("studentid");
		
        String result="";
        
        HttpSession session=req.getSession();
        String userid=(String)session.getAttribute("userid");
		
		sqlOperation sql = new sqlOperation();
		
		if(type==1) {
			int count = sql.getCount("select count(*) from student_test where test_id='"+testid+"'");
			String[] students = sql.getQuerySet("select student_id from student_test where test_id='"+testid+"'",count);
			result = "{\"count\":\""+count+"\""; 
			for(int i=0;i<count;i++){
				result+=",\"studentId"+String.valueOf(i+1)+"\":\""+students[i]+"\",\"studentName"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select user_name from user_inf where user_id='"+students[i]+"'", 1))[0]+"\",\"isFinished"+String.valueOf(i+1)+"\":\""+(sql.getQuerySet("select isFinished from student_test where test_id='"+testid+"' and student_id='"+students[i]+"'", 1))[0]+"\"";
			}
			result +="}";
		}else if(type==2) {
			int count=sql.getCount("select count(*) from have_subject_topic where test_id='"+testid+"' and student_id='"+studentid+"'");
			if(count==0) {
				result = "{\"count\":\""+count+"\",\"isFinished\":\""+1+"\"}";
			}else {
				String isFinished = sql.getQuerySet("select isFinished from have_subject_topic where test_id='"+testid+"' and student_id='"+studentid+"'",count)[0];
				result = "{\"count\":\""+count+"\",\"isFinished\":\""+isFinished+"\"}"; 
			}	
		}else if(type==3) {
			String teacherName = sql.getQuerySet("select user_name from user_inf where user_id='"+userid+"'",1)[0];
			result = "{\"teacherName\":\""+teacherName+"\"}"; 
		}
		
        
        resp.setContentType("application/json;charset=UTF-8");
		PrintWriter out = resp.getWriter();		
		out.write(result);
		
		
    }

}
